'use strict';

const {
	Service
} = require("@ddc391565320/openapi");
const fs = require("fs");
const path = require("path");
var querystring = require("querystring")

const PROD_AK = "AKLTOTg4OGUzZjE0ZGJhNDA4MmIwMGE0YmFlMTZmNmZjMTE";
const PROD_SK = "TTJJeU5qTm1ZVGc1WldNMk5EUXlOV0ZrTTJWaFpEVTVNV1ExTmpRNE5Uaw==";

const serviceInstance = new Service();
serviceInstance.setAccessKeyId(PROD_AK);
serviceInstance.setSecretKey(PROD_SK);
serviceInstance.setHost("visual.volcengineapi.com");

const ServiceName = "cv";
const Action = "FaceSwap";
const Version = "2022-08-31";
exports.main = async (event, context) => {
	// event  = {type:0,data:["http://template.shijianhu.com/image/new/image2/r83k5n.png", "http://template.shijianhu.com/image/new/image4/6rtomf.png"]}
	let data = {};
	// 0是url 1是 base64
	if (event.type == 0) {
		data = {
			image_urls: event.data ,
			req_key: "faceswap",
			face_type: "area",
			do_risk: false
		};
	} else {
		data = {
			binary_data_base64: event.data ,
			req_key: "faceswap",
			face_type: "area",
			do_risk: false
		};
	}

	let param = {
		method: "POST",
		Action,
		Version,
		data: data, // application/x-www-form-urlencoded 需要格式化
		maxBodyLength: Number.POSITIVE_INFINITY, // 防止 axios 报 body 超长
	};
	
	let result;
	try{
	 result = await serviceInstance.fetchOpenAPI(
		param, {
			serviceName: ServiceName,
		}
	);	
	}catch(e){
		//TODO handle the exception
			console.log("imageMergeFace error", JSON.stringify(e));
	}
	

	console.log("imageMergeFace", result.code);

	return result;
};